//go:build windows

package third_program

import (
	net "net/url"
	"os"
	"os/exec"
	"strings"

	"file_explorer/common/consts"
	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"

	"github.com/jan-bar/es"
)

type apiImpl struct{}

func (a *apiImpl) RunCmd(name string, args ...string) {
	realArgs := append([]string{"/C", name}, args...)
	cmd := exec.Command("cmd", realArgs...)
	err := cmd.Run()
	if err != nil {
		log.Error("run cmd failed, name=%v, args=%v, err=%v", name, args, err)
		return
	}
	log.Debug("run cmd success, name=%v, args=%v", name, args)
	return
}

func (a *apiImpl) OpenFile(path string) {
	a.RunCmd("start", "", util.FormatPath(path))
}

func (a *apiImpl) OpenPathWithDefaultFileExplorer(path string) {
	path = util.FormatPath(path)
	if path == "/" {
		path = "explorer"
	}
	a.RunCmd("start", path)
}

func (a *apiImpl) OpenUrlsWithDefaultWebExplorer(urls []string) {
	for _, url := range urls {
		if len(url) == 0 {
			continue
		}
		if !strings.HasPrefix(strings.ToLower(url), "http") {
			url = "https://" + url
		}
		if _, err := net.ParseRequestURI(url); err != nil {
			log.Error("parse uri failed, url=%v, err=%v", url, err)
			continue
		}
		a.RunCmd("start", url)
	}
}

func (a *apiImpl) SearchByEverything(keyword string) ([]*model.FileInfo, error) {
	log.Debug("search by keyword, keyword=%v", keyword)
	// 设置关键词
	err := es.EverythingSetSearch(keyword)
	if err != nil {
		return nil, err
	}

	// 设置查询属性
	err = es.EverythingSetRequestFlags(
		es.EverythingRequestFileName |
			es.EverythingRequestPath |
			es.EverythingRequestSize |
			es.EverythingRequestDateModified)
	if err != nil {
		return nil, err
	}

	// 设置排序方式
	err = es.EverythingSetSort(es.EverythingSortNameAscending)
	if err != nil {
		return nil, err
	}

	// 开始查询
	err = es.EverythingQuery(true)
	if err != nil {
		return nil, err
	}

	// 得到查询结果个数
	num, err := es.EverythingGetNumResults()

	res := make([]*model.FileInfo, 0, num)

	for i := uint32(0); i < num; i++ {
		dir, err := es.EverythingGetResultPath(i)
		if err != nil {
			continue
		}
		name, err := es.EverythingGetResultFileName(i)
		if err != nil {
			continue
		}
		stat, err := os.Stat(util.PathJoin(dir, name))
		if err != nil {
			continue
		}

		fileInfo := &model.FileInfo{
			Name:       name,
			Dir:        dir,
			Type:       consts.FileTypeRegular,
			Size:       stat.Size(),
			ModifyTime: stat.ModTime(),
		}
		if stat.IsDir() {
			fileInfo.Type = consts.FileTypeDir
		}

		res = append(res, fileInfo)
	}

	return res, nil
}
